package com.sanen.flyer.common;

import com.sanen.flyer.entity.FlyObject;
import com.sanen.flyer.main.Game;
import com.sanen.flyer.tool.ImageTool;

import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * @author wsse
 * @date 2018-09-18 9:42
 */
public class Animation {
    FlyObject fly;
    BufferedImage img;
    int size;//图片包含的图像数量
    int index;//当前展示的图片位置
    int playCount = 1;//播放次数 -1,一直轮播

    int width;//图像宽度
    int height;//图像高度
    int imgWidth;//图片宽度
    int imgHeight;//图片高度
    int interval;//图像切换时间
    int time;//播放一轮动画时间
    int x;
    int y;
    int count;

    public Animation(FlyObject fly, BufferedImage img, int size, int time, int playCount) {
        this.fly = fly;
        this.img = img;
        this.imgWidth = (int) (img.getWidth()* Constant.getRatio());
        this.imgHeight = (int) (img.getHeight()* Constant.getRatio());
        this.size = size;
        this.width = imgWidth / size;
        this.height = imgHeight;
        this.time = time;
        this.playCount = playCount;
        this.interval = time / size;
    }

    public void draw(Graphics g) {
        if (playCount != 0) {
            x = fly.getX();
            y = fly.getY();
            g.setClip(x, y, width, height);
            g.drawImage(img, x - index * width, y, imgWidth, imgHeight, null);
            count++;
//            当前播放耗时大于图像切换间隔
            if (count * Game.REFRESH_INTERVAL >= interval) {
                index++;
                count=0;
                if (index >= size) {//一轮动画播放完重置
                    index = 0;
                    playCount--;
                }
            }
        }
    }

    public void setPlayCount(int count) {
        playCount = count;
    }

    public int getPlayCount() {
        return playCount;
    }
}
